import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Icon, Button, Menu, Dropdown, Modal, Table } from 'antd';
import moment from 'moment';
import AderTable from '../../components/AderTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './AdvertiserList.less';
import AdModal from './AdModal';
// import HistoryModal from './HistoryModal';

const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

@connect(state => ({
  advertiser: state.advertiser,
  payment: state.payment,
}))
@Form.create()
export default class AdvertiserList extends PureComponent {
  state = {
    modalVisible: false,
    historyModalVisible: false,
    selectedRows: [],
    formValues: {},
    modalData: {},
    // paymentHistory: [],
    currentAderId: '',
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'advertiser/fetch',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'advertiser/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'advertiser/fetch',
      payload: {},
    });
  };

  handleMenuClick = (e) => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;

    switch (e.key) {
      case 'remove':
        Modal.confirm({
          title: 'Are you sure delete this record?',
          onOk() {
            dispatch({
              type: 'advertiser/remove',
              payload: {
                id: selectedRows.map(row => row.id).join(','),
              },
            });
          },
          // callback: () => {
          //   this.setState({
          //     selectedRows: [],
          //   });
          // },
        });
        break;
      default:
        break;
    }
    this.setState({
      selectedRows: [],
    });
  };

  handleSelectRows = (rows) => {
    this.setState({
      selectedRows: rows,
    });
  };

  handlePayment = (aderId, amount) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'payment/add',
      payload: {
        aderId,
        amount,
        paymentType: 0,
      },
    });
    dispatch({
      type: 'advertiser/fetch',
      payload: {},
    });
  };
  handleEditItem = (flag, payload) => {
    this.setState({
      modalVisible: true,
      selectedRows: [],
      modalData: payload,
    });
  };
  handleShowHistoryModal = (flag, payload) => {
    const { dispatch } = this.props;
    this.setState({
      historyModalVisible: true,
      currentAderId: payload,
      selectedRows: [],
    });
    dispatch({
      type: 'payment/fetch',
      payload: {
        aderId: payload,
      },
    });
  };

  handleSearch = (e) => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        name: fieldsValue.name,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'advertiser/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = (flag) => {
    this.setState({
      modalVisible: !!flag,
      selectedRows: [],
      modalData: {},
    });
  };

  handleHistoryModalVisible = (flag) => {
    this.setState({
      historyModalVisible: !!flag,
    });
  };
  handleHistoryModalOk = () => {
    const downloadDom = document.getElementById('download');
    downloadDom.click();
    this.setState({
      historyModalVisible: false,
      currentAderId: '',
    });
  };

  handleAdd = (ad) => {
    this.props.dispatch({
      type: 'advertiser/add',
      payload: ad,
    });
    this.setState({
      modalVisible: false,
    });
    this.setState({
      modalData: {},
    });
  };

  renderForm() {
    const { getFieldDecorator } = this.props.form;
    const { selectedRows } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <Form.Item label="广告主名称">
              {getFieldDecorator('name')(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col md={9} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            </span>
          </Col>
          <Col md={3} sm={24}>
            {
              selectedRows.length > 0 && (
                <span>
                  <Dropdown overlay={menu}>
                    <Button>
                  批量操作 <Icon type="down" />
                    </Button>
                  </Dropdown>
                </span>
              )
            }
          </Col>
          <Col md={4} sm={24}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新建广告主
            </Button>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { advertiser: { loading: advertiserLoading, data } } = this.props;
    const { payment } = this.props;
    const { selectedRows, modalVisible, modalData,
      historyModalVisible, currentAderId } = this.state;
    // const loadMore = list.length > 0 ? (
    //   <div style={{ textAlign: 'center', marginTop: 16 }}>
    //     <Button onClick={this.fetchMore} style={{ paddingLeft: 48, paddingRight: 48 }}>
    //       {loading ? <span><Icon type="loading" /> 加载中...</span> : '加载更多'}
    //     </Button>
    //   </div>
    // ) : null;


    return (
      <PageHeaderLayout title="广告主列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderForm()}
            </div>
            <AderTable
              selectedRows={selectedRows}
              loading={advertiserLoading}
              data={data}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              onEdit={this.handleEditItem}
              onPay={this.handlePayment}
              onShowHistory={this.handleShowHistoryModal}
            />
          </div>
        </Card>
        <AdModal
          modalVisible={modalVisible}
          onOk={this.handleAdd}
          onCancel={() => this.handleModalVisible()}
          modalData={modalData}
        />
        <a
          id="download"
          href={`http://ad.huolea.com/back_end/payment/excel?aderId=${currentAderId}`}
          style={{ display: 'none' }}
        >下载
        </a>
        <Modal
          title="支付及消耗记录"
          visible={historyModalVisible}
          onOk={this.handleHistoryModalOk}
          onCancel={() => this.handleHistoryModalVisible(false)}
          cancelText="确认"
          okText="导出"
        >
          <Table
            columns={[
              { title: '时间',
                dataIndex: 'date',
                sorter: true,
                render: val => <span>{moment(val).format('YYYY-MM-DD')}</span>,
              },
              { title: '当日消耗', dataIndex: 'dayCost' },
              { title: '当日充值', dataIndex: 'dayIncome' },
              { title: '余额', dataIndex: 'balance' },
            ]}
            loading={payment.loading}
            pagination={false}
            // pagination={{
            //   total: payment.totalElements,
            //   pageSize: payment.size,
            //   current: parseInt(payment.number, 10) + 1 || 1,
            // }}
            // scroll={{ y: 300 }}
            dataSource={payment.data ? payment.data.content : []}
          />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
